package com.zcp.pcsuitall.business;

import com.zcp.pcsuitall.Action;
import com.zcp.pcsuitall.BusinessControl;
import com.zcp.pcsuitall.IDealWithMessage;
import com.zcp.pcsuitall.PictureDealWith;
import com.zcp.pcsuitall.SuitUtil;
import com.zcp.pcsuitall.XmlDataDealWith;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;

import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.LinkedList;

public class PictureManager implements IDealWithMessage{

    private static String TAG="PictureManager";
    @Override
    public boolean dealWith(SocketChannel sc, Action action, Context context) {
        if ("GetPicInfo".equals(action.getName())) {
            getPictureInfo(sc, context, action);
        } else if ("DeletePic".equals(action.getName())) {
            deletePicture(sc, context, action);
        } else if("GetThumbnail".equals(action.getName()))
        {
            getThumbnail(sc, context, action);
        }
        return false;
    }
    
    /**
     * 获取图片信息(去掉应用程序中图片)。
     * @param sc
     * @param context
     */
    private void getPictureInfo(SocketChannel sc, Context context,Action action) {
        Cursor cursor = null;
        HashMap<String, String> thuMap=null;
        
        Cursor cursorInner = null;
        HashMap<String, String> thuMapInner=null;
        try {
            cursor = SuitUtil.getImageInfo(context,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            thuMap = SuitUtil.getThumbnailsImageInfo(context,MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI);
            
//            cursorInner = SuitUtil.getImageInfo(context,MediaStore.Images.Media.INTERNAL_CONTENT_URI);
//            thuMapInner = SuitUtil.getThumbnailsImageInfo(context,MediaStore.Images.Thumbnails.INTERNAL_CONTENT_URI);
            
            StringBuffer buf = new StringBuffer();
            buf.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>GetPicInfo</action><data>");
            //加外部数据库的图片
            addImageData(cursor,buf,thuMap,"out");
            
//            addImageData(cursorInner,buf,thuMapInner,"inner");
            
            buf.append("</data>");
            buf.append("</root>");
            BusinessControl.returnToClient(sc, buf.toString(), context);
        } catch (Exception e) {
            e.printStackTrace();
            BusinessControl.returnToClient(sc,XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()),context);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if(thuMap!=null)
            {
                thuMap.clear();
                thuMap=null;
            }
            
            if (cursorInner != null) {
                cursorInner.close();
            }
            if(thuMapInner!=null)
            {
                thuMapInner.clear();
                thuMapInner=null;
            }
        }
    }
    
    private void addImageData(Cursor cursor,StringBuffer buf,HashMap<String, String> thuMap,String key)
    {
        String id=null;
        String path=null;  
        
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (cursor != null && cursor.moveToFirst()) {
            do {
                path = cursor.getString(1);
                //去掉应用程序中图片
                if (path.contains("drawable") && path.endsWith("png")) {
                    continue;
                }
//                Date date = new Date();s
                    id = cursor.getInt(2) + "";
                    buf.append("<item>");
                    buf.append("<id>" + id + "</id>");
                    buf.append("<picName>" + cursor.getString(0) + "</picName>");
                    buf.append("<picPath>" + path + "</picPath>");
                    buf.append("<scalePicPath>" + thuMap.get(id) + "</scalePicPath>");
                    buf.append("<addTime>" + cursor.getLong(4) + "</addTime>");//拍摄时间单位是毫秒
                    buf.append("</item>");
//                    date.setTime(cursor.getLong(3)*1000);
//                    Log.i("222", key+"||"+id+"||"+cursor.getString(1) + "-----" +dateFormat.format(new Date(cursor.getLong(4)))+"---"+dateFormat.format(date));
               
            } while (cursor.moveToNext());
        }
    }
    /**
     * 删除图片。
     * @param sc
     * @param context
     */
    private void deletePicture(SocketChannel sc, Context context, Action action) {
        Log.v(TAG, "deletePicture ");
        LinkedList<String> ids = XmlDataDealWith.getRegular("id", action.getSource());
        if (ids == null || ids.isEmpty()) {
            BusinessControl.returnToClient(sc, XmlDataDealWith.getErrorString(action.getName(),
                    "6", "action deletePic id is null"), context);
            return;
        }
        StringBuilder whereStr = new StringBuilder();
        whereStr.append(MediaStore.Images.Media._ID).append(" in (");
        int size = ids.size();
        for (int i = 0; i < size; i++) {
            whereStr.append(" " + ids.get(i) + " ");
            if (i < (size - 1)) {
                whereStr.append(",");
            }

        }
        whereStr.append(" ) ");
        
        StringBuilder whereStr2 = new StringBuilder();
        whereStr2.append(MediaStore.Images.Thumbnails.IMAGE_ID).append(" in (");
        size = ids.size();
        for (int i = 0; i < size; i++) {
            whereStr2.append(" " + ids.get(i) + " ");
            if (i < (size - 1)) {
                whereStr2.append(",");
            }

        }
        whereStr2.append(" ) "); 
        
        try {
            context.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    whereStr.toString(), null);
            
            context.getContentResolver().delete(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                    whereStr2.toString(), null);

            BusinessControl
                    .returnToClient(
                            sc,
                            "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>DeletePic</action><data><result>ok</result></data></root>",
                            context);
            ids.clear();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
            BusinessControl.returnToClient(sc,XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()),context);
        }

    }
    
    /**
     * 生成缩略图返回。
     * @param sc
     * @param context
     * @param action
     */
    private void getThumbnail(SocketChannel sc, Context context, Action action) {
        try {
            String id = XmlDataDealWith.getRegularSingle("id", action.getSource());
            
            String readIco = XmlDataDealWith.getRegularSingle("readIco", action.getSource());
            
            long idLong = Long.valueOf(id);
            Bitmap image = Thumbnails.getThumbnail(context.getContentResolver(), idLong,
                    Thumbnails.MICRO_KIND, null);
            String path=SuitUtil.getThumbnailsImageInfoByImageId(context,MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,id);
            
            String result = "fail";
            String data = "";
            if (image != null) {
                result = "ok";
                if("true".equals(readIco))
                {
                data = PictureDealWith.getStringFromBitmap(image);
                }
            }
            StringBuffer buf = new StringBuffer();
            buf.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>GetThumbnail</action><data><item>");
            buf.append("<id>" + id + "</id>");
            buf.append("<ico>" + data + "</ico>");
            buf.append("<result>" + result + "</result>");
            buf.append("<path>" +  path + "</path>");
            buf.append("</item>");
            buf.append("</data>");
            buf.append("</root>");

            BusinessControl.returnToClient(sc, buf.toString(), context);
            Log.i("222", "getThumbnail "+result);
        } catch (Exception e) {
            e.printStackTrace();
            BusinessControl.returnToClient(sc,XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()),context);
        }
        
        
    }

    
}
